<?php

namespace app\api\controller;
use data\Json;
use think\Request;
use think\Cache;
use JPush\Client as JPush;
/**
 * 社群
 */
class Community extends Base
{
    protected $user_model = null;
    protected $token = null;

    public function _initialize()
    {
        $this->user_model = model('User');
        $this->token = request()->header('token');
    }

    public function sms()
    {
        $mobile = $data['mobile'] = input("mobile");
        $vali = $this->validate($data,'User.sms');
        if($vali !== true) return Json::json_send($vali);
        return $this->sendSMS($mobile);
    }

    public function verifyCode()
    {
        if($request->isPost())
        { 
            $data = input();
            $vali = $this->validate($data,'User.validate');
            if($vali !== true) return Json::json_send($vali);
            if($data['code']==Cache::get($mobile))
            {
                return Json::json_send(0);
            }
            return Json::json_send(403);
        }
        return Json::json_send(4);
    }

    public function login(Request $request)
    {
        if($request->isPost())
        { 
            $data = input();
            $vali = $this->validate($data,'User.validate');
            if($vali !== true) return Json::json_send($vali);
            $result=$this->user_model->login($data['mobile'],$data['code']);
            if(!$result)
            {
                return Json::json_send(2);
            }
            return Json::json_send(0,'',$result);
        }
        return Json::json_send(4);
    }

    public function register(Request $request)
    {
        if($request->isPost())
        {
            $role = input('role');
            if(!$role)return Json::json_send(10005);
            $scenes = $role == 2?'User.member_register':'User.community_register';
            $data = input();
            $vali = $this->validate($data,$scenes);
            if($vali !== true) return Json::json_send($vali);
            return Json::json_send(model('User')->register($data));
        }
        
        return Json::json_send(4);
    }

        // 用户登录
    public function logout()
    {
        $user = $this->user_model->getUserInfo($this->token);
        if(!$user){return Json::json_send(1);}

        cache(config('tokenPrefix').$this->token, NULL);
        cache(config('tokenAndUserPrefix') . $user['id'], NULL);
        return Json::json_send(0,'退出成功');
    }
}
